﻿using System;
using System.Linq;
using IInject.Extensibility;
using IInject.Tests.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace IInject.Tests
{
	[TestClass]
	public class ExtensibilityTests
	{
		[TestMethod]
		public void AddExtensionTest()
		{
			var container = new Container();
			IExtension extension = new MockExtension(container);
			container.AddExtension(extension);

			extension = container.Single();
			Assert.IsInstanceOfType(extension, typeof(MockExtension));
		}

		[TestMethod]
		public void AddExtensionGenericTest()
		{
			var container = new Container();
			container.AddExtension(new MockExtension(container));

			var extension = container.Single();
			Assert.IsInstanceOfType(extension, typeof(MockExtension));
		}

		[TestMethod]
		public void RemoveExtensionTest()
		{
			var container = new Container();
			IExtension extension = new MockExtension(container);
			container.AddExtension(extension);

			if (!container.RemoveExtension(extension))
			{
				Assert.Fail("Failed to remove extension.");
			}
			
			extension = container.SingleOrDefault();
			Assert.IsNull(extension);
		}

		[TestMethod]
		public void RemoveExtensionGenericTest()
		{
			var container = new Container();
			var extension = new MockExtension(container);
			container.AddExtension(extension);

			if (!container.RemoveExtension(extension))
			{
				Assert.Fail("Failed to remove extension.");
			}

			var iExtension = container.SingleOrDefault();
			Assert.IsNull(iExtension);
		}

		[TestMethod]
		public void ExtensionGetEventHandlersFiredTest()
		{
			var container = new Container();
			var extension = new MockExtension(container);
			container.AddExtension(extension);

			container.Set<IDependencyTest, DependencyTest>();

			Assert.IsTrue(extension.ItemRegisteringFired);
			Assert.IsTrue(extension.ItemRegisteredFired);

			container.Get<IDependencyTest>();

			Assert.IsTrue(extension.ItemResolvingFired);
		}

		[TestMethod]
		public void ExtensionGetAllEventHandlersFiredTest()
		{
			var container = new Container();
			var extension1 = new MockExtension(container);
			var extension2 = new MockExtension(container);
			container.AddExtension(extension1);
			container.AddExtension(extension2);

			container.SetAll<IDependencyTest>(new[] { new DependencyTest(), new DependencyTest() });

			Assert.IsTrue(extension1.ItemRegisteringFired);
			Assert.IsTrue(extension1.ItemRegisteredFired);
			Assert.IsTrue(extension2.ItemRegisteringFired);
			Assert.IsTrue(extension2.ItemRegisteredFired);

			container.GetAll<IDependencyTest>();

			Assert.IsTrue(extension1.ItemResolvingFired);
			Assert.IsTrue(extension2.ItemResolvingFired);
		}
	}
}
